<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="88px">
          <el-form-item label="团购券券码" prop="code">
            <el-input v-model="queryParams.code" placeholder="请输入团购券券码" clearable style="width: 240px"
              @keyup.enter="handleQuery" />
          </el-form-item>

          <el-form-item label="团购券名称" prop="ticketName">
            <el-input v-model="queryParams.ticketName" placeholder="请输入团购券名称" clearable style="width: 240px"
              @keyup.enter="handleQuery" />
          </el-form-item>

          <el-form-item label="订单号" prop="orderId">
            <el-input v-model="queryParams.orderId" placeholder="请输入订单号" clearable style="width: 240px"
              @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="会员姓名" prop="memberName">
            <el-input v-model="queryParams.memberName" placeholder="请输入会员姓名" clearable style="width: 240px"
              @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="核销时间">
            <el-date-picker v-model="valueTime" type="daterange" unlink-panels range-separator="-"
              start-placeholder="开始时间" end-placeholder="结束时间" :shortcuts="shortcuts" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <!--        <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['primary:ticketWriteOff:add']">新增</el-button>
          </el-col> -->
          <!--          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['primary:ticketWriteOff:edit']">修改</el-button>
          </el-col> -->
          <!--          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['primary:ticketWriteOff:remove']">删除</el-button>
          </el-col> v-hasPermi="['primary:ticketWriteOff:export']"-->
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="ticketWriteOffList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />

        <el-table-column label="团购券券码" align="center" prop="code" />
        
        <el-table-column label="核销时间" align="center" prop="createTime" />

        <el-table-column label="团购券名称" align="center" prop="ticketName" />


        <el-table-column label="团购券平台类型" align="center">
          <template #default="scope">
            <dict-tag :options="sys_ostype_type" :value="scope.row.osType" />
          </template>
        </el-table-column>
        
        <el-table-column label="订单号" align="center" prop="orderId" />

        <el-table-column label="会员姓名" align="center" prop="memberName" />

        <!--        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['primary:ticketWriteOff:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['primary:ticketWriteOff:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column> -->
      </el-table>

      <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改团购核销记录对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="ticketWriteOffFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="团购券券码" prop="code">
          <el-input v-model="form.code" placeholder="请输入团购券券码" />
        </el-form-item>
        <el-form-item label="加密的券码信息" prop="encryptedCode">
          <el-input v-model="form.encryptedCode" placeholder="请输入加密的券码信息" />
        </el-form-item>
        <el-form-item label="团购券名称" prop="ticketName">
          <el-input v-model="form.ticketName" placeholder="请输入团购券名称" />
        </el-form-item>
        <el-form-item label="代表一张券码的标识" prop="certificateId">
          <el-input v-model="form.certificateId" placeholder="请输入代表一张券码的标识" />
        </el-form-item>
        <el-form-item label="代表券码一次核销的唯一标识(验券时返回)" prop="verifyId">
          <el-input v-model="form.verifyId" placeholder="请输入代表券码一次核销的唯一标识(验券时返回)" />
        </el-form-item>
        <el-form-item label="券码消费的商户" prop="accountId">
          <el-input v-model="form.accountId" placeholder="请输入券码消费的商户" />
        </el-form-item>
        <el-form-item label="券码消费的门店" prop="poiId">
          <el-input v-model="form.poiId" placeholder="请输入券码消费的门店" />
        </el-form-item>
        <el-form-item label="订单号" prop="orderId">
          <el-input v-model="form.orderId" placeholder="请输入订单号" />
        </el-form-item>
        <el-form-item label="团购券使用者id" prop="memberId">
          <el-input v-model="form.memberId" placeholder="请输入团购券使用者id" />
        </el-form-item>
        <el-form-item label="团购券使用者姓名" prop="memberName">
          <el-input v-model="form.memberName" placeholder="请输入团购券使用者姓名" />
        </el-form-item>
        <el-form-item label="健身房id" prop="gymId">
          <el-input v-model="form.gymId" placeholder="请输入健身房id" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="TicketWriteOff" lang="ts">
  import { listTicketWriteOff, getTicketWriteOff, delTicketWriteOff, addTicketWriteOff, updateTicketWriteOff } from '@/api/primary/ticketWriteOff';
  import { TicketWriteOffVO, TicketWriteOffQuery, TicketWriteOffForm } from '@/api/primary/ticketWriteOff/types';

  const { proxy } = getCurrentInstance() as ComponentInternalInstance;
  const { sys_ostype_type } = toRefs<any>(proxy?.useDict("sys_ostype_type"));
  const ticketWriteOffList = ref<TicketWriteOffVO[]>([]);
  const buttonLoading = ref(false);
  const loading = ref(true);
  const showSearch = ref(true);
  const ids = ref<Array<string | number>>([]);
  const single = ref(true);
  const multiple = ref(true);
  const total = ref(0);
  const valueTime = ref('')
  const queryFormRef = ref<ElFormInstance>();
  const ticketWriteOffFormRef = ref<ElFormInstance>();
  const shortcuts = [
    {
      text: '七天内核销',
      value: () => {
        const end = new Date()
        const start = new Date()
        start.setDate(start.getDate() - 7)
        return [start, end]
      },
    },
    {
      text: '十五天内核销',
      value: () => {
        const end = new Date()
        const start = new Date()
        start.setDate(start.getDate() - 15)
        return [start, end]
      },
    },
    {
      text: '三十天内核销',
      value: () => {
        const end = new Date()
        const start = new Date()
        start.setDate(start.getDate() - 30)
        return [start, end]
      },
    }
  ]
  const dialog = reactive<DialogOption>({
    visible: false,
    title: ''
  });

  const initFormData : TicketWriteOffForm = {
    id: undefined,
    code: undefined,
    encryptedCode: undefined,
    ticketName: undefined,
    certificateId: undefined,
    verifyId: undefined,
    accountId: undefined,
    poiId: undefined,
    osType: undefined,
    orderId: undefined,
    memberId: undefined,
    memberName: undefined,
    gymId: undefined
  }
  const data = reactive<PageData<TicketWriteOffForm, TicketWriteOffQuery>>({
    form: { ...initFormData },
    queryParams: {
      pageNum: 1,
      pageSize: 10,
      startTime: undefined,
      endTime: undefined,
      code: undefined,
      encryptedCode: undefined,
      ticketName: undefined,
      certificateId: undefined,
      verifyId: undefined,
      accountId: undefined,
      poiId: undefined,
      osType: undefined,
      orderId: undefined,
      memberId: undefined,
      memberName: undefined,
      gymId: undefined,
      params: {
      }
    },
    rules: {
      id: [
        { required: true, message: "主键id不能为空", trigger: "blur" }
      ],
      code: [
        { required: true, message: "团购券券码不能为空", trigger: "blur" }
      ],
      encryptedCode: [
        { required: true, message: "加密的券码信息不能为空", trigger: "blur" }
      ],
      ticketName: [
        { required: true, message: "团购券名称不能为空", trigger: "blur" }
      ],
      certificateId: [
        { required: true, message: "代表一张券码的标识(验券时返回)不能为空", trigger: "blur" }
      ],
      verifyId: [
        { required: true, message: "代表券码一次核销的唯一标识(验券时返回)不能为空", trigger: "blur" }
      ],
      accountId: [
        { required: true, message: "券码消费的商户不能为空", trigger: "blur" }
      ],
      poiId: [
        { required: true, message: "券码消费的门店不能为空", trigger: "blur" }
      ],
      osType: [
        { required: true, message: "团购券的平台类型：1：抖音，2：美团，3：大众点评不能为空", trigger: "change" }
      ],
      orderId: [
        { required: true, message: "订单号不能为空", trigger: "blur" }
      ],
      memberId: [
        { required: true, message: "团购券使用者id不能为空", trigger: "blur" }
      ],
      memberName: [
        { required: true, message: "团购券使用者姓名不能为空", trigger: "blur" }
      ],
      gymId: [
        { required: true, message: "健身房id不能为空", trigger: "blur" }
      ]
    }
  });

  const { queryParams, form, rules } = toRefs(data);

  const updateExpireEndTime = () => {
    console.log('11111111111111111111111')
    if (valueTime.value) {
      const StartTime = new Date(valueTime.value[0]).toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit'
      }).replace(/\//g, '-');
      queryParams.value.startTime = StartTime + ' 00:00:00';

      const EndTime = new Date(valueTime.value[1]).toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit'
      }).replace(/\//g, '-');
      queryParams.value.endTime = EndTime + ' 23:59:59';

    } else {
      queryParams.value.startTime = undefined
      queryParams.value.endTime = undefined
    }

  }

  /** 查询团购核销记录列表 */
  const getList = async () => {
    updateExpireEndTime()
    loading.value = true;
    const res = await listTicketWriteOff(queryParams.value);
    ticketWriteOffList.value = res.rows;
    total.value = res.total;
    loading.value = false;
  }

  /** 取消按钮 */
  const cancel = () => {
    reset();
    dialog.visible = false;
  }

  /** 表单重置 */
  const reset = () => {
    form.value = { ...initFormData };
    ticketWriteOffFormRef.value?.resetFields();
  }

  /** 搜索按钮操作 */
  const handleQuery = () => {
    queryParams.value.pageNum = 1;
    getList();
  }

  /** 重置按钮操作 */
  const resetQuery = () => {
    valueTime.value = undefined
    queryFormRef.value?.resetFields();
    handleQuery();
  }

  /** 多选框选中数据 */
  const handleSelectionChange = (selection : TicketWriteOffVO[]) => {
    ids.value = selection.map(item => item.id);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
  }

  /** 新增按钮操作 */
  const handleAdd = () => {
    reset();
    dialog.visible = true;
    dialog.title = "添加团购核销记录";
  }

  /** 修改按钮操作 */
  const handleUpdate = async (row ?: TicketWriteOffVO) => {
    reset();
    const _id = row?.id || ids.value[0]
    const res = await getTicketWriteOff(_id);
    Object.assign(form.value, res.data);
    dialog.visible = true;
    dialog.title = "修改团购核销记录";
  }

  /** 提交按钮 */
  const submitForm = () => {
    ticketWriteOffFormRef.value?.validate(async (valid : boolean) => {
      if (valid) {
        buttonLoading.value = true;
        if (form.value.id) {
          await updateTicketWriteOff(form.value).finally(() => buttonLoading.value = false);
        } else {
          await addTicketWriteOff(form.value).finally(() => buttonLoading.value = false);
        }
        proxy?.$modal.msgSuccess("修改成功");
        dialog.visible = false;
        await getList();
      }
    });
  }

  /** 删除按钮操作 */
  const handleDelete = async (row ?: TicketWriteOffVO) => {
    const _ids = row?.id || ids.value;
    await proxy?.$modal.confirm('是否确认删除团购核销记录编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
    await delTicketWriteOff(_ids);
    proxy?.$modal.msgSuccess("删除成功");
    await getList();
  }

  /** 导出按钮操作 */
  const handleExport = () => {
    proxy?.download('primary/ticketWriteOff/export', {
      ...queryParams.value
    }, `ticketWriteOff_${new Date().getTime()}.xlsx`)
  }

  onMounted(() => {
    getList();
  });
</script>